package cn.wx.autoconfiguration;

import cn.wx.DefaultWxCpConfigStorageFactory;
import cn.wx.WxCpConfigStorageFactory;
import cn.wx.WxCpServiceRegisterPostProcessor;
import cn.wx.api.WxCpMultipleService;
import cn.wx.api.impl.WxCpMultipleServiceImpl;
import cn.wx.properties.Agent;
import cn.wx.properties.WxCpProperties;
import me.chanjar.weixin.cp.api.WxCpService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import static cn.wx.properties.WxCpProperties.PREFIX;


@Configuration
@ConditionalOnClass(WxCpService.class)
@EnableConfigurationProperties(WxCpProperties.class)
@ConditionalOnProperty(prefix = PREFIX, value = "enabled", havingValue = "true", matchIfMissing = true)
public class WxCpAutoConfiguration {

    private final WxCpProperties properties;

    public WxCpAutoConfiguration(WxCpProperties properties) {
        this.properties = properties;
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean
    public WxCpMultipleService wxCpMultipleService() {
        return new WxCpMultipleServiceImpl(properties.getName());
    }

    @Bean
    @ConditionalOnMissingBean
    public WxCpConfigStorageFactory<Agent> wxCpConfigStorageFactory() {
        return new DefaultWxCpConfigStorageFactory();
    }

    @Bean
    @ConditionalOnMissingBean(name = "wxCpServiceRegisterPostProcessor")
    public WxCpServiceRegisterPostProcessor wxCpServiceRegisterPostProcessor(WxCpConfigStorageFactory<Agent> wxCpConfigStorageFactory) {
        return new WxCpServiceRegisterPostProcessor(properties, wxCpConfigStorageFactory);
    }
}
